--[[

     Licensed under GNU General Public License v2
      * (c) 2013, Luca CPZ

--]]

local helpers  = require("lain.helpers")
local wibox    = require("wibox")
local tonumber = tonumber

-- {thermal,core} temperature info
-- lain.widget.temp

local function factory(args)
    args           = args or {}

    local temp     = { widget = args.widget or wibox.widget.textbox() }
    local timeout  = args.timeout or 5
    -- local tempfile = args.tempfile or "/sys/devices/platform/coretemp.0/hwmon/hwmon6/temp1_input"
    -- local temppath = "/sys/devices/platform/coretemp.0/hwmon"
    local temp_cmd = "sensors |grep Tctl | awk '{print $2}'"
    local liquid_temp_cmd = "/home/ethan/miniconda3/envs/nzxt_test/bin/liquidctl status | grep temperature | awk '{print $4}'"
    local gpu_temp_cmd = "/opt/bin/nvidia-smi -q -i 0 -d TEMPERATURE |grep 'GPU Current'| awk '{print $5}'"
    -- "/sys/devices/virtual/thermal/thermal_zone0/temp"
    local settings = args.settings or function() end

    function temp.update()
        temp_f, err = io.popen(temp_cmd)
        coretemp_now = string.sub(temp_f:read(), 2) or "N/A"

        liquid_f, err = io.popen(liquid_temp_cmd)
        liquid_temp = string.sub(liquid_f:read(), 1) or "N/A"

        gpu_f, err = io.popen(gpu_temp_cmd)
        gpu_temp = string.sub(gpu_f:read(), 1) or "N/A"

        widget = temp.widget
        settings()

        -- helpers.async({"find", temppath, "-type", "f", "-name", "*temp*_input"}, function(f)
            -- temp_now = {}
            -- local temp_fl, temp_value
            -- for t in f:gmatch("[^\n]+") do
                -- temp_fl = helpers.first_line(t)
                -- if temp_fl then
                    -- temp_value = tonumber(temp_fl)
                    -- temp_now[t] = temp_value and temp_value/1e3 or temp_fl
                -- end
            -- end
            -- coretemp_now = temp_now[tempfile] or "N/A"
            -- widget = temp.widget
            -- settings()
        -- end)
    end

    helpers.newtimer("thermal", timeout, temp.update)

    return temp
end

return factory
